<script src="https://cdn.bootcss.com/plupload/2.1.8/plupload.full.min.js"></script>
<script type="text/javascript" charset="utf-8" src="/uedit/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="https://cdn.staticfile.org/ueditor/1.4.3/ueditor.all.js"> </script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" charset="utf-8" src="/uedit/lang/zh-cn/zh-cn.js"></script>
<link rel="stylesheet" href="/css/topicApps_add.css">
<div class="main layui-clear">
	<div class="wrap layui-clear">
		<div class="layui-bar">
   	  		<div class="layui-breadcrumbs">
   	  			<a class="home" href="/"></a>
				<i class="layui-icon">&#xe602;</i>
				<a href="/topic/topicIndex">谈天说地</a>
				<i class="layui-icon">&#xe602;</i>
   	  			<a href="#">发布帖子</a>
   	  		</div>
      	</div>
		<div class="layui-form layui-form-pane">
		    <form action="/topic/save.html" method="post">
		     <input type="hidden" name="topicFiles" lay-verify="checkImg">
		   	 <div class="layui-form-item">
		        <label for="L_title" class="layui-form-label">请选择板块</label>
		        <div class="layui-input-block">
					<select name="cateparent" id="selectBlock"  required lay-verify="required" placeholder="请选择" lay-filter="selectBlock"  >
						<#if blockList?? && blockList??>
						<#list blockList as list>
							<#if list.type=="板块">
								<option value="${list.id!''}">${list.blockname!''}</option>
								<#if !(blockParentId??)>
									<#assign blockParentId="${list.id!''}">
								</#if>
							</#if>
						</#list>
						</#if>
					</select>
					 <select name="cate" id="selectCategory"  required lay-verify="required" placeholder="请选择" >
	                	<#if blockList?? && blockList??>
	                	<#list blockList as list>
							<#if (list.type=="分类" && list.parentid== blockParentId)>
								<option value="${list.id!''}">${list.blockname!''}</option>
							</#if>
						</#list>
						</#if>
					</select>
		        </div>
		      </div>
		      <div class="layui-form-item">
		        <label for="L_title" class="layui-form-label">请输入标题</label>
		        <div class="layui-input-block">
		          <input type="text" id="L_title" name="title" required lay-verify="required|size80|checkContent" autocomplete="off"  class="layui-input input-height-36">
		        </div>
		      </div>
		      <div class="layui-form-item">
		        <label for="content" class="layui-form-label" style="top: -2px;">请输入正文</label>
		        <div class="layui-input-block">
		          <textarea id="content" name="content" required lay-verify="content|checkContent|checkUeditorImg"   style="height: 194px;"></textarea>
		        </div>
		      </div>
		      <div class="layui-form-item">
		        <div class="layui-input-block">
					<a class="button-upload" id="UploadButton">上传文件</a>	<label style="color:red;;margin-left:10px">附件最多5个</label>        
					<div class="upload-progress">
						
					</div>
				</div>
		      </div>
		      <div class="layui-form-item">
		        <div class="layui-input-block">
		          <input type="text" id="inputCode" required lay-verify="code" autocomplete="off" class="layui-input layui-input-code">
		          <div class="code-show" id="checkCode" onclick="createCode()" > </div>
		          <span class="code-show-push"  onclick="createCode()" >刷新</span>
		        </div>
		       </div>
		      <div class="layui-form-item">
		        <div class="layui-input-block">
		          <button class="button-add" id="button-one" lay-submit  lay-filter="formDemo">提交</button>
		          <a href="#" class="button-add layui-hide"  id="button-two">正在提交...</a>
		        </div>
		      </div>
		    </form>
		  </div>
		</div>
	</div>
<script>

var layedit , index, code;
var listCategory = [], AttachmentList = [];
var url = "/topicupload";
<#list blockList as list >  
	listCategory.push({"parentid":"${list.parentid!''}","id": "${list.id!''}","blockname": "${list.blockname!''}"})
</#list>  
layui.use(['form' , 'layedit'], function(){
  var form = layui.form() ;
  layedit = layui.layedit;
  //根据选择显示
  form.on('select(selectBlock)', function(data){
	$("#selectCategory option").remove();
   	$.each(listCategory, function(index,item){
   		if(data.value == item.parentid){
   			$("#selectCategory").append("<option value='"+item.id+"'>"+item.blockname+"</option>")
   		}
   	})
   	if($("#selectCategory").find("option").length == 0){ //内部元素为空 重新渲染报错
   		$("#selectCategory").append("<option value=''>请选择</option>")
   	}
   	form.render('select');
  }); 
  form.verify({
	  checkContent: function(value, item){ 
		  if(item.name=="content"){
			  value = ue.getContentTxt()
		  }
		  var status = "";
		  if(value!=""){
			  $.ajax({
				  type:"POST",
				  url:"/checkConent",
				  data: {"content": value},
				  async: false,
				  success:function(data){
					 
					   var result = JSON.parse(data.requestmsg);
					   var resultsType = result.data[0].results[0].label;
					   if(result.data[0].results[0].suggestion!="pass"){
						   switch (resultsType)
							  {
							  case "spam":
								  status='您的内容包含垃圾信息';
							    break;
							  case "ad":
								  status='您的内容包含广告信息';
							    break;
							  case "politics":
								  status='您的内容包含渉政信息';
							    break;
							  case "terrorism":
								  status='您的内容包含暴恐信息';
							    break;
							  case "abuse":
								  status='您的内容包含辱骂信息';
							    break;
							  case "porn":
								  status='您的内容包含色情信息';
							    break;
							  case "flood":
								  status='您的内容包含灌水信息';
							    break;
							  case "contraband":
								  status='您的内容包含违禁信息';
							    break;
							  }
					   }
				  },
				  error:function(data){
					  console.log(data.requestmsg)
				  },
			  })
			  if(status!=""){
				  return status;
			  }
		  }
	  },
	  checkUeditorImg: function(value, item){ 
		  	 var data = [], status={}, imgReg = /<img.*?(?:>|\/>)/gi;
			 //匹配src属性
			 var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
			 var arr = ue.getContent().match(imgReg);
			 if(arr){
				 for (var i = 0; i < arr.length; i++){
					 if(arr[i].match(srcReg)[1].indexOf("http://")<0){
						 if(arr[i].match(srcReg)[1].indexOf("http://")<0){
							 data.push({
						        "dataId": i,
						        "url": "http://www.myboxlab.com"+arr[i].match(srcReg)[1],
						  		"time":new Date()
						      }); 
						 }
					 }
				 }
			 }
			 if(data.length>10){
				  return "最多上传10张图片！";
			 }else if(data.length>0){
				 var msg = msgSatatus(data);
			    if(msg!=""){
				  return msg;
			    }
			 }else{}
	  },
	  checkImg: function(value, item){ 
		  var data = [],status={};
		  if(AttachmentList.length>0){
			 $.each(AttachmentList,function(index,item){
				 var imgType = [".jpeg",".jpg","gif",".bmp",".png"];
				 var imgName = "."+item.enclosureurl.split(".")[1];
				 if(imgType.indexOf(imgName) >=0){
					 data.push({
				        "dataId": item.deleteId,
				        "url": "https://www.myboxlab.com/"+item.enclosureurl,
				  		"time":new Date()
				      }) 
				 }
			}) 
			var msg = msgSatatus(data);
		    if(msg!=""){
			  return msg;
		    }
		  }
	  },
	  code: function(value, item){ 
	    if(value.length <= 0) {
	      return '请输入验证码';
	     }
	     else if(value.toUpperCase() != code.toUpperCase()) {
	    	createCode();   
	   		return '验证码输入有误！';
	     }
	     else {} 
	  },
	  content: function(value, item){ 
		value = ue.getContent()
    	if(value.length <= 0) {
	      return '请输入正文';
	     }
	  },
	  size80: function(value, item){ 
	    	if(value.replace(/[^\u0000-\u00ff]/g,"***").length >= 78) {
		      return '标题最多26字';
		     }
		  },
	  
	}); 
  
  
  //提交
  form.on('submit(formDemo)', function(data){
	  $("#button-one").addClass("layui-hide");
	  $("#button-two").removeClass("layui-hide").addClass("layui-show");
	  $("input[name=topicFiles]").val(JSON.stringify(AttachmentList));
  }); 
});

UE.Editor.prototype.placeholder = function (justPlainText) {
	var _editor = this;
	_editor.addListener("focus", function () {
		var localHtml = _editor.getPlainTxt();
		if ($.trim(localHtml) === $.trim(justPlainText)) {
			_editor.setContent(" ");
		}
	});
	_editor.addListener("blur", function () {
		var localHtml = _editor.getContent();
		if (!localHtml) {
			_editor.setContent(justPlainText);
		}
	});
	_editor.ready(function () {
		_editor.fireEvent("blur");
	});
};
var ue = UE.getEditor('content', {
	//这里可以选择自己需要的工具按钮名称
	toolbars: [
		['Source','|', 'undo', 'redo', 'removeformat', 'backcolor', 'formatmatch','|', 'italic', 'underline', 'Bold', 'test',
			'forecolor','|', 'justifyleft', 'justifycenter', 'justifyright','|','insertorderedlist' ,'|',
			'fontfamily', 'fontsize','|',
			 'simpleupload','emotion'
		]
	],
	wordCount: false,					//开启字数统计
	elementPathEnabled : false,
	retainOnlyLabelPasted : true,
});
//placeholder内容(只能是文本内容)
ue.placeholder("请输入正文");
createCode();
function createCode() {
 code = "";
 var codeLength = 4; //验证码的长度
 var checkCode = document.getElementById("checkCode");
 var codeChars = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
      'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
	  '1','2','3','4','5','6','7','8','9','0'); //所有候选组成验证码的字符，当然也可以用中文的
 for(var i = 0; i < codeLength; i++) {
  var charNum = Math.floor(Math.random() * 52);
  code += codeChars[charNum];
 }
 if(checkCode) {
  checkCode.className = "code-show";
  checkCode.innerHTML = code;
 }
}


//上传初始化
var uploader = new plupload.Uploader({
	browse_button: 'UploadButton', //触发文件选择对话框的按钮，为那个元素id
	url: url, //服务器端的上传页面地址
	flash_swf_url: '${ctxStatic}/plupload/js//Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
	silverlight_xap_url: '${ctxStatic}/plupload/js/Moxie.xap', //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
	filters : {
	 	max_file_size : '40mb',
	 	prevent_duplicates: "true" //不允许选取重复文件
	},
});

//在实例对象上调用init()方法进行初始化
uploader.init();
//绑定各种事件，并在事件监听函数中做你想做的事
uploader.bind('FilesAdded',function(uploader, files) {
	$("#inforShow").removeClass("layui-hide");
	if(uploader.files.length > 5){ //  最多上传5个附件
        uploader.splice(5,999);
        layer.msg('最多上传5个附件！', {icon: 1})
    }
	$.each(files ,function(index,item){
		if($(".upload-progress .upload-progress-li").length <= 4){ 
			$(".upload-progress").append('<div id="progress'+item.id+'" class="upload-progress-li"><span title="'+item.name+'">'+item.name+'</span><div class="upload-progress-bar"><span class="color"></span></div></div>');
		}
	})
	
	uploader.start()
	
})

//上传后回调
uploader.bind('FileUploaded', function(uploader,UploadProgress, responseObject) {
	var obj = $.parseJSON(responseObject.response);
	var json = {};
	json.enclosurename = obj.fileName;
	json.enclosureurl = obj.filePath;
	json.enclosureid = obj.fileId;
	json.topicid = '${topic.id!''}';
	json.filesize = Math.ceil(UploadProgress.origSize / 1024);
	AttachmentList.push(json);
	$("#progress"+UploadProgress.id).append('<i id="'+UploadProgress.id+'" class="layui-icon" onclick="deleteA(this,\''+obj.fileId+'\')">&#x1006;</i>')
	$("#progress"+UploadProgress.id + " .color").text("100%");
});
uploader.bind('UploadProgress', function(up, file) {
  $("#progress"+file.id + " .color").css("width",file.percent + "%");
});
//报错
uploader.bind('Error',function(up,err) {
	 if(err.code == '-600'){
		 layer.msg('文件最多可上传40M', {icon: 5});
    }	else if (err.code == '-602'){
  	  layer.msg('文件重复！', {icon: 5});
    }	
	 console.log(err)	
	
});
function deleteA(i,enclosureid,fileId){
	var deleteListId = $(i).attr("id");
	uploader.removeFile(deleteListId);
	$(i).parents(".upload-progress-li").remove();
	$.each(AttachmentList, function(index,item){
		if(item.enclosureid == enclosureid){
			AttachmentList.splice(index, 1);
			return false;
		}
	})
}
</script>